package com.cdd.agent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cdd.common.core.controller.BaseController;
import com.cdd.common.core.domain.Result;
import com.cdd.common.core.page.TableDataInfo;
import com.cdd.common.domain.entity.*;
import com.cdd.agent.api.mapper.AgentUserMapper;
import com.cdd.agent.api.mapper.AgentUserMessageMapper;
import com.cdd.agent.api.mapper.AgentUserRecordsMapper;
import com.cdd.agent.api.service.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("")
public class AgentController extends BaseController {

    @Resource
    AgentUserRecordsService agentUserRecordsService;
    
    @Resource
    AppUserService appUserService;
    
    @Resource
    AgentUserService agentUserService;
    
    @Resource
    AgentUserWithdrawService agentUserWithdrawService;
    
    @Resource
    AgentUserMoneyRecordService agentUserMoneyRecordService;
    
    @Resource
    AgentUserMessageService agentUserMessageService;

    @Resource
    AppOrderService appOrderService;

    @RequestMapping("/agent/index")
    public Result index() {
        Map<String, Object> data = new HashMap<>();
        int allUser, allUserMan, allUserWoman, newUser, newUserMan, newUserWoman;
        BigDecimal rechargeMoneyToday, withdrawMoneyToday, moneyToday;

        Integer userId = getUserId();
        AgentUserRecordsMapper recordsMapper = agentUserRecordsService.getBaseMapper();
        List<AgentUserRecords> list = recordsMapper.list(userId);
        allUser = list.size();
        allUserMan = (int) list.stream().filter(e -> e.getSex() == 1).count();
        allUserWoman = (int) list.stream().filter(e -> e.getSex() == 2).count();

        List<AgentUserRecords> list1 = recordsMapper.todayNewUser(userId);
        newUser = list1.size();
        newUserMan = (int) list1.stream().filter(e -> e.getSex() == 1).count();
        newUserWoman = (int) list1.stream().filter(e -> e.getSex() == 2).count();

        List<AgentUserRecords> agentUserRecords = recordsMapper.selectList(
                new LambdaQueryWrapper<AgentUserRecords>()
                        .eq(AgentUserRecords::getParentUserId, userId)
        );
        String subUserIds = agentUserRecords.stream().map(e -> e.getUserId().toString()).collect(Collectors.joining(","));
        rechargeMoneyToday = appOrderService.rechargeToday(subUserIds);
        withdrawMoneyToday = appOrderService.withdrawToday(subUserIds);
        moneyToday = agentUserMoneyRecordService.getBaseMapper().todayMoney(userId);

        AgentUser user = agentUserService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<AgentUser>()
                        .eq(AgentUser::getUserId, userId)
        );

        data.put("allUser", allUser);
        data.put("allUserMan", allUserMan);
        data.put("allUserWoman", allUserWoman);
        data.put("newUser", newUser);
        data.put("newUserMan", newUserMan);
        data.put("newUserWoman", newUserWoman);
        data.put("rechargeMoneyToday", rechargeMoneyToday);
        data.put("withdrawMoneyToday", withdrawMoneyToday);
        data.put("money", user == null ? 0 : user.getMoney());
        data.put("moneyToday", moneyToday);
        return success(data);
    }

    @RequestMapping("/userList")
    public TableDataInfo getAllUser(Integer userId) {
        List<AgentUserRecords> records = agentUserRecordsService.getBaseMapper().selectList(
                new LambdaQueryWrapper<AgentUserRecords>()
                        .eq(AgentUserRecords::getParentUserId, userId)
        );
        if (CollectionUtils.isEmpty(records)) {
            return getDataTable(Collections.emptyList());
        }
        startPage();
        List<AppUser> maps = appUserService.getBaseMapper().selectList(
                new LambdaQueryWrapper<AppUser>()
                        .in(AppUser::getId, records.stream().map(AgentUserRecords::getUserId).collect(Collectors.toList()))
        );
        return getDataTable(maps);
    }

    @RequestMapping("/withdraw")
    public Result withdraw(Integer userId, BigDecimal money) {
        AgentUserMapper agentUserMapper = agentUserService.getBaseMapper();
        AgentUser agentUser = agentUserMapper.getUserId(userId);
        if(agentUser == null || agentUser.getMoney().compareTo(BigDecimal.ZERO) == 0) {
            return error("余额不足");
        }
        if (agentUser.getMoney().compareTo(money) >= 0) {
            AgentUserWithdraw param = new AgentUserWithdraw();
            param.setAgentUserId(userId);
            param.setMoney(money);
            param.setStatus(0);
            param.setCreateTime(new Date());
            agentUserWithdrawService.withdraw(param, agentUser);
            return success("成功");
        } else {
            return error("余额不足");
        }
    }

    @RequestMapping("/messageList")
    public TableDataInfo userList(Integer userId) {
        startPage();
        AgentUserMessageMapper userMessageMapper = agentUserMessageService.getBaseMapper();
        List<AgentUserMessage> list = userMessageMapper.selectList(
                new LambdaQueryWrapper<AgentUserMessage>()
                        .eq(AgentUserMessage::getUserId, userId)
                        .orderByDesc(AgentUserMessage::getId)
        );
        if(!list.isEmpty()) {
            userMessageMapper.update(null,
                    new LambdaUpdateWrapper<AgentUserMessage>()
                            .set(AgentUserMessage::getIsRead, 1)
                            .in(AgentUserMessage::getId, list.stream().map(AgentUserMessage::getId).collect(Collectors.toList()))
            );
        }
        return getDataTable(list);
    }
}
